package com.zx.util;

import com.google.common.io.BaseEncoding;
import com.zx.link.entity.Link;
import com.zx.link.entity.LinkType;
import java.util.List;

/**
 * @version v1.0
 * @Project: link
 * @Title: LinkToHtml
 * @Description: 转为html书签
 * @author: zhangxue
 * @date: 2017年3月4日下午8:48:54
 * @company: ......
 * @email: 1039791136@qq.com
 * @Copyright: Copyright (c) 2017
 */
public class LinkToHtml {

    public static String toHTML(List<Link> linkList, List<LinkType> types) {
        long datetime = System.currentTimeMillis();
        StringBuffer html = new StringBuffer();
        html.append("<!DOCTYPE NETSCAPE-Bookmark-file-1>\r\n");
        html.append("<META HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=UTF-8\">\r\n");
        html.append("<TITLE>Bookmarks</TITLE>\r\n");
        html.append("<H1>Bookmarks</H1>\r\n");
        html.append("<DL>\r\n");
        html.append("<DT><H3 ADD_DATE=" + datetime + " LAST_MODIFIED=" + datetime
                + " PERSONAL_TOOLBAR_FOLDER=\"true\">书签栏</H3>\r\n");

        html.append("<DL>\r\n");

        for (LinkType type : types) {
            datetime++;
            html.append(
                    "<DT><H3 ADD_DATE=" + datetime + " LAST_MODIFIED=" + datetime + ">" + type.getName() + "</H3>\r\n");
            html.append("<DL>\r\n");
            for (Link link : linkList) {
                if (type.getId().intValue() == link.getTid().intValue()) {
                    datetime++;
                    String a = toA(link, datetime);
                    html.append("<DT>").append(a).append("</DT>\r\n");
                }
            }
            html.append("</DL>\r\n");
            html.append("</DT>\r\n");
        }
        html.append("</DL>\r\n");
        html.append("</DT>\r\n");
        html.append("</DL>\r\n");
        return html.toString();
    }


    private static String toA(Link link, long datetime) {
        StringBuffer a = new StringBuffer();
        a.append("<A HREF=\"").append(link.getUrl()).append("\" ADD_DATE=\"").append(datetime).append("\" ");
        byte[] icon = link.getIcon();
        if (icon != null) {
            String base64Str = BaseEncoding.base64().encode(icon);
            a.append(" ICON=\"data:image/png;base64,").append(base64Str).append("\"");
        } else {
            a.append(" ICON='' ");
        }
        a.append(">").append(link.getName()).append("</A>");
        return a.toString();
    }
}
